package com.lanmaoly.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JDK动态代理test
 * @author Administrator
 * @param <T>
 */
public class JDKDynamicTest<T> implements InvocationHandler {

    private Object target;

    public JDKDynamicTest(Object target) {
        this.target = target;
    }

    public T createProxy() {
        Class<?> aClass = target.getClass();
        ClassLoader classLoader = aClass.getClassLoader();
        Class<?>[] interfaces = aClass.getInterfaces();
        Object instance = Proxy.newProxyInstance(classLoader, interfaces, this);
        return (T) instance;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("11111111111111");
        Object invoke = method.invoke(target, args);
        System.out.println("22222222222222");
        return invoke;
    }

    public static void main(String[] args) {
        JDKDynamicTest<UserServiceTest> jdkDynamicTest = new JDKDynamicTest<>(new UserServiceTestImpl());
        UserServiceTest userServiceTest = jdkDynamicTest.createProxy();
        userServiceTest.print();
    }
}
